package com.hjh.java.rabbitmq.service.simple;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Component
public class ImportReceiver {

    @RabbitHandler
    public void process1(String hello) {
        System.out.println("Receiver1 : " + hello);
    }


    /**
     * @param message     :解码后的消息
     * @param deliveryTag :使用@Header接口获取messageProperties中的DELIVERY_TAG属性。
     * @param channel     : 接受消息所使用的信道
     */
    @RabbitListener(queues = "queue.name.import")
    @Transactional
    public void process1(@Payload String message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws Exception {
//    if(message.equals("1")){
//      int i = 1/0;
//    }
//    channel.basicAck(deliveryTag,false);
//    System.out.print("这里是接收者1答应消息： ");
//    System.out.println("SYS_TOPIC_ORDER_CALCULATE_ZZ_FEE process1  : " + message);


        Action action = Action.ACCEPT;
        try {

            log.info("|message:{}",message);
            // 如果成功完成则action=Action.ACCEPT
            if(message.equals("1")){
                int i= 1/0;
            }

        } catch (Exception e) {
            // 根据异常种类决定是ACCEPT、RETRY还是 REJECT
            log.error("",e);
        } finally {
            // 通过finally块来保证Ack/Nack会且只会执行一次
            if (action == Action.ACCEPT) {
                channel.basicAck(deliveryTag,false);
            } else if (action == Action.RETRY) {
                channel.basicNack(deliveryTag, false, true);
            } else {
                channel.basicNack(deliveryTag, false, false);
            }
        }
    }
}

enum Action {
    ACCEPT,  // 处理成功
    RETRY,   // 可以重试的错误
    REJECT,  // 无需重试的错误
}